from pipei_data.api_requests import get_details_api, cps_books_api, search_api
from pipei_data.db_operations import DatabaseOperations
from tools.base_tools import get_current_and_previous_day_strings
import requests
from loguru import logger


class ActionHandler(DatabaseOperations):
    def __init__(self):
        super().__init__()
        self.action_dict = {
            "article": {
                "func": get_details_api,
                "base_url": "https://scapi.tayunapi.com/funcLog/article",
                "table": "course_pay_info",
            },
            "activity": {
                "func": get_details_api,
                "base_url": "https://scapi.tayunapi.com/funcLog/activity",
                "table": "course_pay_info",
            },
            "chatgpt": {
                "func": get_details_api,
                "base_url": "https://scapi.tayunapi.com/funcLog/chatgpt",
                "table": "course_pay_info",
            },
            "contract": {
                "func": get_details_api,
                "base_url": "https://scapi.tayunapi.com/funcLog/contract",
                "table": "course_pay_info",
            },
            "course": {
                "func": get_details_api,
                "base_url": "https://scapi.tayunapi.com/funcLog/course",
                "table": "course_pay_info",
            },
            "video": {
                "func": get_details_api,
                "base_url": "https://scapi.tayunapi.com/funcLog/video",
                "table": "course_pay_info",
            },
            "cps_book": {
                "func": cps_books_api,
                "base_url": "http://tuicps.tylahs.com/v1/book/getBookInfo",
                "table": "course_pay_info",
            },
            "bookcps": {
                "func": cps_books_api,
                "base_url": "http://tuicps.tylahs.com/v1/book/getBookInfo",
                "table": "course_pay_info",
            },
            "banner": {
                "func": get_details_api,
                "base_url": "https://scapi.tayunapi.com/funcLog/banner",
                "table": "course_pay_info",
            },
            "search": {
                "func": search_api,
                "base_url": "https://scapi.tayunapi.com/funcLog/searchList",
                "table": "search_pay_info",
            },
        }

    def get_action_info(self, order_info):
        days_filter = get_current_and_previous_day_strings(order_info["create_time"])
        url = "https://scapi.tayunapi.com/funcLog/logs"
        params = {
            "start": days_filter[0],
            "end": days_filter[1],
            "page": 1,
            "rows": 10,
            "user_id": order_info["user_id"],
            "sort": "desc",
            "orderby": "id",
            "create_time": order_info["create_time"],
        }
        response = requests.get(url, params=params)
        logger.debug(response.url)
        return response.json()

    def get_order_action(self, action_info, order_info):
        for action in action_info["list"]:
            if action["action"] in self.action_dict:
                return {
                    **action,
                    "order_no": order_info["order_no"],
                    "order_key": order_info["key"],
                }
        return {}

    def get_api_desc(self, order_action_info):
        item_id = order_action_info["item_id"]
        if item_id == 0:
            return -2

        action_name = order_action_info["action"]
        api_base_url = self.action_dict[action_name]["base_url"]

        func = self.action_dict[action_name]["func"]
        if action_name == "search":
            return func(
                order_action_info["create_time"],
                order_action_info["user_id"],
                api_base_url,
                order_action_info["item_id"],
            )
        else:
            res_desc = func(action_name, api_base_url, item_id)
            # 检查API返回的数据类型，防止list类型导致的mapping错误
            if isinstance(res_desc, list) or not res_desc:
                return -2  # 数据为空或格式错误，返回匹配失败状态
            return {**res_desc, **order_action_info}

    def format_info_data(self, info_data):
        keys = [
            "order_no",
            "detail_id",
            "info_title",
            "cover",
            "id",
            "module",
            "action",
            "item_custom",
            "create_time",
            "category_id",
            "name",
            "order_key",
        ]
        selected_data = {k: info_data.get(k) for k in keys if k in info_data}
        if "create_time" in selected_data:
            selected_data["action_create_time"] = selected_data.pop("create_time")
        if "id" in selected_data:
            selected_data["action_id"] = selected_data.pop("id")
        return selected_data

    def process_order_info(self, order_info, df_intype):
        # try:
        action_info = self.get_action_info(order_info)
        order_action_info = self.get_order_action(action_info, order_info)

        if not order_action_info:
            return self.execute_sql_update(order_info["order_no"], -2)

        # 搜索的走这套逻辑
        if order_action_info["action"] == "search":
            info_data = self.get_api_desc(order_action_info)
            if not info_data:
                return self.execute_sql_update(order_info["order_no"], -2)
            info_data["order_no"] = order_info["order_no"]
            info_data["status"] = order_info["status"]
        else:
            if not order_action_info.get("item_id"):
                info_data = -2
            else:
                info_data = self.get_api_desc(order_action_info)

            if isinstance(info_data, (int, float)) or (
                isinstance(info_data, (list, dict)) and not info_data
            ):
                return self.execute_sql_update(order_info["order_no"], -2)
            info_data = self.format_info_data(info_data)
            #
            if info_data["order_key"] != info_data["action"]:
                new_key_name = (
                    "bookcps"
                    if info_data["action"] == "cps_book"
                    else info_data["action"]
                )
                # 安全获取intype配置，防止索引越界
                filtered_df = df_intype[df_intype["key"] == new_key_name]
                if filtered_df.empty:
                    logger.error(f"❌ 无法找到key='{new_key_name}'的配置信息，跳过key更新")
                    # 如果找不到配置，跳过key更新，继续使用原有的key
                else:
                    intype_dict = filtered_df.iloc[0].to_dict()
                    sql = f"""
                        UPDATE pay SET `key` = '{new_key_name}', in_type = '{intype_dict['id']}', title = '{intype_dict['title']}'
                        WHERE order_no = '{info_data['order_no']}'
                    """
                    self.execute_sql(sql)

        self.update_to_mysql(
            info_data, table=self.action_dict[info_data["action"]]["table"]
        )
        logger.info(f"{info_data['order_no']} -> 更新成功")
        # except Exception as err:
        #     logger.error(f"{order_info['order_no']}, 处理失败, {err}")
        #     self.execute_sql_update(order_info["order_no"], -1)
